package com.lc.user.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.lc.user.bo.RegisterUser;
import com.lc.user.dao.UserMapper;
import com.lc.user.pojo.User;
import com.lc.user.service.CodeFeign;
import com.lc.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CodeFeign codeFeign;

    @Override
    public User findUserById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public User findUserByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int register(RegisterUser user) {
        //check null
        if(user == null || user.getEmail() == null || user.getPassword() == null || user.getCode() == null){
            return 1;
        }
        if(userMapper.findByEmail(user.getEmail()) != null){
            System.out.println("邮箱已经被注册: " + user.getEmail());
            return 1;
        }
        //check code
        int res = codeFeign.validateCode(user.getEmail(),user.getCode());
        if(res != 0){
            return res;
        }
        User insertUser = new User();
        insertUser.setEmail(user.getEmail());
        insertUser.setPassword(user.getPassword());
        return userMapper.insert(insertUser) > 0 ? 0 : 1;
    }

    @Override
    public User login(User user) {
        User u = userMapper.findByEmail(user.getEmail());
        if(u == null){
            return null;
        }
        if(!user.getPassword().equals(u.getPassword())){
            return null;
        }
        String token = UUID.randomUUID().toString();
        u.setToken(token);
        userMapper.setToken(u);
        return u;
    }

    @Override
    public User findByToken(String token) {
        return token != null ? userMapper.findByToken(token) : null;
    }
}
